package com.itmaster;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.itmaster.app.viewmodel.LoginViewModel;

/**
 * @author Fernando.Perez
 */
public class LoginActivity extends Activity {

	private static final String TAG = "ITMaster Main Activity";
	private LoginViewModel viewModel;
	protected ProgressDialog progressDialog;

	/**
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		viewModel = new LoginViewModel(this);
		
		Log.i(TAG, "onCreate()");

		Button loginButton = (Button) findViewById(R.id.loginButton);

		loginButton.setOnClickListener(new OnClickListener() {

			/**
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						login();						
					}
				}).start();

				progressDialog = new ProgressDialog(LoginActivity.this);
				progressDialog.setMessage(getResources().getString(R.string.loading));
				progressDialog.show();
			}
		});
		
	}

	protected void login() {
		final EditText usernameInput = (EditText) findViewById(R.id.usernameInput);
		final EditText passwordInput = (EditText) findViewById(R.id.passwordInput);

		viewModel.login(usernameInput.getText().toString(), passwordInput.getText().toString());
	}

	/**
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		super.onStart();
		
		Log.i(TAG, "onStart()");
	}

	/**
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		
		Log.i(TAG, "onResume()");
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		Log.i(TAG, "onPause()");
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		
		Log.i(TAG, "onStop()");
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		Log.i(TAG, "onDestroy()");
	}

	/**
	 * 
	 */
	public void startLogin() {
		// Do nothing...
	}

	/**
	 * @param e
	 */
	public void finishLogin(Exception e) {
		Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
	}

	public void loginSuccess() {
		startActivity(new Intent(this, DashboardActivity.class));
	}

	public void loginFail() {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				progressDialog.dismiss();
				Toast.makeText(LoginActivity.this, R.string.loginFail, Toast.LENGTH_SHORT).show();				
			}
		});
	}
}